package designmodel;

import java.util.ArrayList;
import java.util.List;

/**
 * @author songZiHao
 * @version 1.0.0
 * @ClassName ObserverModel.java
 * @Description TODO
 * @createTime 2021年01月23日 11:18:00
 */
public class ObserverModel {
	/**
	 * 观察者接口
	 */
	public static abstract class MyObserver {
		/**
		 * 改变事件
		 * @param state 旧值
		 * @param update 新值
		 */
		 void changeEvent(Integer state, Integer update){};

		protected Subject subject;
	}

	public static class MyObserver1 extends MyObserver{
		public MyObserver1(Subject subject) {
			this.subject=subject;
			subject.addObserver(this);
		}

		@Override
		public void changeEvent(Integer state, Integer update) {
			System.out.println("MyObserver1 receive change Event");
		}

	}

	public static class MyObserver2 extends MyObserver{

		public MyObserver2(Subject subject) {
			this.subject=subject;
			subject.addObserver(this);
		}
		@Override
		public void changeEvent(Integer state, Integer update) {
			System.out.println("MyObserver2 receive change Event");
		}
	}

	public static class MyObserver3 extends MyObserver{
		public MyObserver3(Subject subject) {
			this.subject=subject;
			subject.addObserver(this);
		}
		@Override
		public void changeEvent(Integer state, Integer update) {
			System.out.println("MyObserver3 receive change Event");
		}
	}
	public static class Subject{
		public List<MyObserver> observerList=new ArrayList<>(4);

		public Integer state=0;
		/**
		 * 添加观察者
		 * @param myObserver 观察者
		 */
		public void addObserver(MyObserver myObserver){
			observerList.add(myObserver);
		}

		/**
		 * 更新并通知
		 * @param update 更新的值
		 */
		public void update(Integer update){
			Integer temp=state;
			this.state=update;
			notifyAllObserver(state,update);
		}

		private void notifyAllObserver(Integer state,Integer update) {
			for (MyObserver observer : observerList) {
				observer.changeEvent(state,update);
			}
		}
	}

	public static void main(String[] args) {
		Subject subject = new Subject();

		new MyObserver1(subject);
		new MyObserver2(subject);
		new MyObserver3(subject);

		System.out.println("First state change: 15");
		subject.update(15);
		System.out.println("Second state change: 10");
		subject.update(10);
	}
}
